package com.itheima.d6_tcp3;

import java.io.*;
import java.net.Socket;

public class ServerTread implements Runnable{
    Socket accept;

    public ServerTread(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        BufferedReader br=null;
        try {
            InputStream is = accept.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            while (true) {
                String s = br.readLine();
                System.out.println(s);
                if(s==null){
                    //当对象等于null时，说明断开了连接，删除掉这个断开连接的对象
                    Server.list.remove(accept);
                    break;
                }
                //遍历list集合，拿到每一个accept对象
                for (Socket socket : Server.list) {
                    //给所有非自己的socket发送数据
                    if(socket!=accept){
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        bw.write(s);//写数据
                        bw.newLine();
                        bw.flush();
                    }

                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                accept.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
